from db import db
from util import config

import sha
import random

class Accounts(db.Table):
    
    def _init(self):
        self._conn.execute('''
            create table accounts
            (uid INTEGER PRIMARY KEY, username STRING NOT NULL, password STRING NOT NULL)
            ''')
           
    def _drop(self):
        self._conn.execute('''
            drop table accounts
            ''')
        
    def authenticate(self, username, raw_password):
        # TODO: experiment with case when the username, password aren't provided
        [result] = self._conn.execute('''
            SELECT * FROM accounts WHERE username=?''', (username,))
        enc_password = result['password']
        algo, salt, hash = enc_password.split('$')
        return (hash == sha.new(salt+raw_password).hexdigest())
        
    def create_user(self, username, password):
        algo = 'sha1'
        salt = sha.new(str(random.random())).hexdigest()[:5]
        hash = sha.new(salt+password).hexdigest()
        password = '%s$%s$%s' % (algo, salt, hash)
        id = random.randint(0,1000000) #1 in a million!
        self._conn.execute('''
            INSERT INTO accounts VALUES (?,?,?) ''', (id, username, password))
        return id
    
    def user_exists(self, username):
        [result] = self._conn.execute(""" 
            SELECT COUNT(*) as count FROM accounts WHERE username=?""", (username,))
        print result
        return result['count'] == 1
    
    @staticmethod
    def instance():
        database = db.get_database(
                    config.get('fv.accounts', 'db-dir'),
                    config.get('fv.accounts', 'db-file'))
        return database.get_or_create(Accounts)
        